<template>
  <view class="calendar-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="title">备考日历</view>
      <view class="subtitle">有规划的复习更高效</view>
    </view>

    <!-- 日历头部 -->
    <view class="calendar-header">
      <view class="month-navigator">
        <view class="prev-btn" @tap="prevMonth">
          <text class="calendar-icon">◀</text>
        </view>
        <view class="current-month">{{ currentYear }}年{{ currentMonth + 1 }}月</view>
        <view class="next-btn" @tap="nextMonth">
          <text class="calendar-icon">▶</text>
        </view>
      </view>
      <view class="weekdays">
        <view class="weekday" v-for="day in weekdays" :key="day">{{ day }}</view>
      </view>
    </view>

    <!-- 日历主体 -->
    <view class="days-grid">
      <view
        class="day-cell"
        v-for="(day, index) in days"
        :key="index"
        :class="{
          'not-current-month': !day.isCurrentMonth,
          today: day.isToday,
          'has-events': day.events && day.events.length > 0,
        }"
        @tap="selectDay(day)"
      >
        <view class="day-number">{{ day.day }}</view>
        <view class="day-events-indicator" v-if="day.events && day.events.length > 0">
          <view
            class="event-dot"
            v-for="(event, i) in day.events.slice(0, 3)"
            :key="i"
            :style="{ backgroundColor: event.color }"
          ></view>
        </view>
      </view>
    </view>

    <!-- 重要考研日期提醒 -->
    <view class="important-dates">
      <view class="section-title">重要日程</view>
      <scroll-view scroll-y class="dates-scroll">
        <view class="date-item" v-for="(event, index) in calendarEvents" :key="index">
          <view class="date-marker" :style="{ backgroundColor: themeColor }"></view>
          <view class="date-content">
            <view class="date-title">{{ event.eventTitle }}</view>
            <view class="date-time">{{ event.eventDate }} {{ event.eventTime }}</view>
          </view>
          <view class="delete-btn" @tap.stop="confirmDeleteEvent(event.id)">
            <text class="delete-icon">×</text>
          </view>
        </view>
        <view class="empty-plan" v-if="calendarEvents.length === 0">
          <text>暂无日程，点击右下角按钮添加</text>
        </view>
      </scroll-view>
    </view>

    <!-- 添加事件浮动按钮 -->
    <view class="floating-button" @tap="showAddEvent = true">
      <text class="plus-icon">+</text>
    </view>

    <!-- 添加事件弹窗 -->
    <view class="modal-overlay" v-if="showAddEvent" @tap="showAddEvent = false">
      <view class="event-modal" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">添加事件</text>
          <text class="close-btn" @tap="showAddEvent = false">×</text>
        </view>
        <view class="modal-content">
          <view class="form-group">
            <text class="form-label">事件标题</text>
            <input
              type="text"
              class="form-input"
              v-model="newEvent.title"
              placeholder="请输入事件标题"
            />
          </view>
          <view class="form-group">
            <text class="form-label">日期</text>
            <picker mode="date" :value="newEvent.date" @change="dateChange" class="form-picker">
              <view class="picker-value">{{ newEvent.date || '请选择日期' }}</view>
            </picker>
          </view>
          <view class="form-group">
            <text class="form-label">时间</text>
            <picker mode="time" :value="newEvent.time" @change="timeChange" class="form-picker">
              <view class="picker-value">{{ newEvent.time || '请选择时间' }}</view>
            </picker>
          </view>
        </view>
        <view class="modal-footer">
          <view class="form-button cancel" @tap="showAddEvent = false">取消</view>
          <view class="form-button submit" @tap="addEvent">保存</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { queryStudyCalendar, addStudyCalendarEvent, deleteStudyCalendarEvent } from '@/api/calendar'

export default {
  data() {
    return {
      // 星期
      weekdays: ['日', '一', '二', '三', '四', '五', '六'],

      // 当前选中日期
      currentDate: new Date(),

      // 显示添加事件弹窗
      showAddEvent: false,

      // 新事件表单
      newEvent: {
        title: '',
        date: '',
        time: '',
      },

      // 固定使用主题色
      themeColor: '#9370DB',

      // 日历事件
      calendarEvents: [],

      // 日历数据
      days: [],
    }
  },

  computed: {
    currentYear() {
      return this.currentDate.getFullYear()
    },
    currentMonth() {
      return this.currentDate.getMonth()
    },
  },

  methods: {
    // 切换到上个月
    prevMonth() {
      this.currentDate = new Date(this.currentYear, this.currentMonth - 1, 1)
      this.generateCalendar()
    },

    // 切换到下个月
    nextMonth() {
      this.currentDate = new Date(this.currentYear, this.currentMonth + 1, 1)
      this.generateCalendar()
    },

    // 选择日期
    selectDay(day) {
      if (day.isCurrentMonth) {
        this.currentDate = new Date(this.currentYear, this.currentMonth, day.day)
        // 预设日期到表单
        const formattedDate = `${this.currentYear}-${String(this.currentMonth + 1).padStart(
          2,
          '0',
        )}-${String(day.day).padStart(2, '0')}`
        this.newEvent.date = formattedDate
        // 显示添加事件弹窗
        this.showAddEvent = true
      }
    },

    // 生成日历数据
    generateCalendar() {
      const year = this.currentYear
      const month = this.currentMonth

      // 获取这个月的第一天是星期几
      const firstDay = new Date(year, month, 1).getDay()

      // 获取这个月的天数
      const daysInMonth = new Date(year, month + 1, 0).getDate()

      // 获取上个月的天数
      const daysInLastMonth = new Date(year, month, 0).getDate()

      // 今天的日期
      const today = new Date()
      const isCurrentMonth = today.getFullYear() === year && today.getMonth() === month
      const currentDay = today.getDate()

      const calendarDays = []

      // 添加上个月的日期
      for (let i = firstDay - 1; i >= 0; i--) {
        calendarDays.push({
          day: daysInLastMonth - i,
          isCurrentMonth: false,
          isToday: false,
          events: [],
        })
      }

      // 添加这个月的日期
      for (let i = 1; i <= daysInMonth; i++) {
        calendarDays.push({
          day: i,
          isCurrentMonth: true,
          isToday: isCurrentMonth && i === currentDay,
          events: this.getMockEvents(i),
        })
      }

      // 添加下个月的日期以填满日历
      const remainingDays = 42 - calendarDays.length
      for (let i = 1; i <= remainingDays; i++) {
        calendarDays.push({
          day: i,
          isCurrentMonth: false,
          isToday: false,
          events: [],
        })
      }

      this.days = calendarDays
    },

    // 模拟一些事件数据
    getMockEvents(day) {
      const events = []
      if (day % 7 === 0) {
        events.push({ title: '每周复习', color: this.themeColor })
      }
      if (day === 15) {
        events.push({ title: '模拟考试', color: this.themeColor })
        events.push({ title: '政治强化', color: this.themeColor })
      }
      if (day === 20) {
        events.push({ title: '英语背单词', color: this.themeColor })
      }
      return events
    },

    // 日期选择器变化事件
    dateChange(e) {
      this.newEvent.date = e.detail.value
    },

    // 时间选择器变化事件
    timeChange(e) {
      this.newEvent.time = e.detail.value
    },

    // 获取日历事件数据
    fetchCalendarEvents() {
      uni.showLoading({
        title: '加载中...',
      })

      queryStudyCalendar()
        .then((res) => {
          const result = res.data
          if (result.code === 200 && result.data) {
            this.calendarEvents = result.data

            // 更新日历上的事件标记
            this.updateCalendarWithEvents()
          } else {
            uni.showToast({
              title: '获取日程失败',
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          console.error('获取日历事件失败:', err)
          uni.showToast({
            title: '网络异常，请重试',
            icon: 'none',
          })
        })
        .finally(() => {
          uni.hideLoading()
        })
    },

    // 更新日历上的事件标记
    updateCalendarWithEvents() {
      // 更新日历数据中的事件信息
      if (this.days && this.days.length > 0) {
        this.days.forEach((day) => {
          if (day.isCurrentMonth) {
            // 找出当天的所有事件
            const date = `${this.currentYear}-${String(this.currentMonth + 1).padStart(
              2,
              '0',
            )}-${String(day.day).padStart(2, '0')}`
            const eventsForDay = this.calendarEvents.filter((event) => event.eventDate === date)

            if (eventsForDay.length > 0) {
              day.events = eventsForDay.map((event) => ({
                title: event.eventTitle,
                color: this.themeColor,
              }))
            }
          }
        })
      }
    },

    // 获取用户ID
    getUserId() {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          const userInfoObj = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
          console.log('获取到的用户信息:', userInfoObj)
          return userInfoObj.id || null
        }
        return null
      } catch (error) {
        console.error('获取用户ID失败:', error)
        return null
      }
    },

    // 确认删除事件
    confirmDeleteEvent(eventId) {
      if (!eventId) return

      uni.showModal({
        title: '提示',
        content: '确定要删除此日程?',
        success: (res) => {
          if (res.confirm) {
            this.deleteEvent(eventId)
          }
        },
      })
    },

    // 删除事件
    deleteEvent(eventId) {
      uni.showLoading({
        title: '删除中...',
      })

      deleteStudyCalendarEvent(eventId)
        .then((res) => {
          const result = res.data
          if (result.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            })
            // 重新获取日历事件
            this.fetchCalendarEvents()
          } else {
            uni.showToast({
              title: result.info || '删除失败',
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          console.error('删除事件失败:', err)
          uni.showToast({
            title: '网络异常，请重试',
            icon: 'none',
          })
        })
        .finally(() => {
          uni.hideLoading()
        })
    },

    // 添加事件
    addEvent() {
      if (!this.newEvent.title.trim()) {
        uni.showToast({
          title: '请输入事件标题',
          icon: 'none',
        })
        return
      }

      if (!this.newEvent.date) {
        uni.showToast({
          title: '请选择日期',
          icon: 'none',
        })
        return
      }

      // 获取用户ID
      const userId = this.getUserId()
      if (!userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none',
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login',
          })
        }, 1500)
        return
      }

      uni.showLoading({
        title: '添加中...',
      })

      // 格式化日期和时间为后端需要的格式
      const eventDate = this.formatDateForBackend(this.newEvent.date)
      const eventTime = this.formatTimeForBackend(this.newEvent.time)

      const eventData = {
        userId: Number(userId), // 确保userId是数字类型
        eventTitle: this.newEvent.title,
        eventDate: eventDate,
        eventTime: eventTime,
      }

      console.log('提交日历事件数据:', JSON.stringify(eventData))

      addStudyCalendarEvent(eventData)
        .then((res) => {
          console.log('服务器响应:', JSON.stringify(res))
          if (res.statusCode === 400) {
            console.error('请求错误 (400):', res)
            uni.showToast({
              title: '请求格式错误',
              icon: 'none',
            })
            return
          }

          const result = res.data
          if (result.code === 200) {
            uni.showToast({
              title: '添加成功',
              icon: 'success',
            })

            // 关闭弹窗
            this.showAddEvent = false

            // 重置表单
            this.newEvent.title = ''
            this.newEvent.date = ''
            this.newEvent.time = ''

            // 重新获取数据
            this.fetchCalendarEvents()
          } else {
            uni.showToast({
              title: result.info || '添加失败',
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          console.error('添加事件失败:', err)
          uni.showToast({
            title: '网络异常，请重试',
            icon: 'none',
          })
        })
        .finally(() => {
          uni.hideLoading()
        })
    },

    // 时间格式转换为后端需要的格式
    formatTimeForBackend(timeStr) {
      if (!timeStr) return '00:00:00'
      // 如果只有时分，添加秒
      if (timeStr.length === 5) {
        return timeStr + ':00'
      }
      return timeStr
    },

    // 日期格式转换为后端需要的格式
    formatDateForBackend(dateStr) {
      if (!dateStr) return ''
      // 保持原格式，确保是yyyy-MM-dd格式
      return dateStr
    },
  },

  // 生命周期钩子
  mounted() {
    // 初始化日历
    this.generateCalendar()

    // 获取日历事件
    this.fetchCalendarEvents()
  },

  // 每次页面显示时刷新数据
  onShow() {
    this.fetchCalendarEvents()
  },
}
</script>

<style lang="scss">
@import '@/styles/variables.scss';

.calendar-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 180rpx;

  .header {
    padding: 60rpx 40rpx 30rpx;
    background: linear-gradient(180deg, $theme-color 0%, $light-theme-color 100%);
    color: #fff;
    border-radius: 0 0 30rpx 30rpx;

    .title {
      font-size: 40rpx;
      font-weight: bold;
    }

    .subtitle {
      font-size: 26rpx;
      margin-top: 10rpx;
      opacity: 0.8;
    }
  }

  .calendar-header {
    background-color: #fff;
    margin: 30rpx;
    border-radius: 20rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .month-navigator {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      background-color: $theme-color;
      color: #fff;

      .current-month {
        font-size: 32rpx;
        font-weight: bold;
      }

      .prev-btn,
      .next-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.2);

        .calendar-icon {
          font-size: 24rpx;
        }
      }
    }

    .weekdays {
      display: flex;
      background-color: #f9f9f9;
      border-bottom: 1px solid #f0f0f0;

      .weekday {
        flex: 1;
        text-align: center;
        padding: 20rpx 0;
        font-size: 26rpx;
        color: #666;

        &:first-child,
        &:last-child {
          color: $theme-color;
        }
      }
    }
  }

  .days-grid {
    display: flex;
    flex-wrap: wrap;
    background-color: #fff;
    margin: 0 30rpx 30rpx;
    border-radius: 0 0 20rpx 20rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .day-cell {
      width: calc(100% / 7);
      height: 90rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 10rpx 0;
      position: relative;
      box-sizing: border-box;
      border-bottom: 1px solid #f9f9f9;

      &.not-current-month {
        color: #ccc;
      }

      &.today {
        background-color: rgba(147, 112, 219, 0.1);

        .day-number {
          background-color: $theme-color;
          color: #fff;
        }
      }

      &.has-events {
        .day-number {
          font-weight: bold;
        }
      }

      .day-number {
        width: 44rpx;
        height: 44rpx;
        line-height: 44rpx;
        text-align: center;
        font-size: 24rpx;
        border-radius: 50%;
      }

      .day-events-indicator {
        display: flex;
        justify-content: center;
        margin-top: 6rpx;

        .event-dot {
          width: 10rpx;
          height: 10rpx;
          border-radius: 50%;
          margin: 0 2rpx;
        }
      }
    }
  }

  .important-dates {
    margin: 0 30rpx 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }

    .dates-scroll {
      max-height: 350rpx;
    }

    .date-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .date-marker {
        width: 16rpx;
        height: 16rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }

      .date-content {
        flex: 1;

        .date-title {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .date-time {
          font-size: 24rpx;
          color: #999;
          margin-top: 8rpx;
        }
      }

      .delete-btn {
        padding: 10rpx 20rpx;

        .delete-icon {
          font-size: 40rpx;
          color: #999;
          font-weight: bold;
        }

        &:active {
          opacity: 0.7;
        }
      }
    }
  }

  .floating-button {
    position: fixed;
    right: 40rpx;
    bottom: 140rpx;
    width: 100rpx;
    height: 100rpx;
    background-color: $theme-color;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 8rpx 16rpx rgba(147, 112, 219, 0.4);
    z-index: 10;

    .plus-icon {
      color: #fff;
      font-size: 60rpx;
      font-weight: bold;
    }
  }

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
  }

  .event-modal {
    width: 650rpx;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;

    .modal-header {
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #f5f5f5;

      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .close-btn {
        font-size: 40rpx;
        color: #999;
      }
    }

    .modal-content {
      padding: 30rpx;
      max-height: 700rpx;
      overflow-y: auto;

      .form-group {
        margin-bottom: 30rpx;

        .form-label {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 16rpx;
          display: block;
        }

        .form-input,
        .form-picker {
          width: 100%;
          height: 80rpx;
          border: 1rpx solid #eee;
          border-radius: 8rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          box-sizing: border-box;
        }

        .picker-value {
          line-height: 80rpx;
          color: #333;
        }
      }
    }

    .modal-footer {
      padding: 20rpx 30rpx;
      display: flex;
      justify-content: flex-end;
      border-top: 1rpx solid #f5f5f5;

      .form-button {
        padding: 0 40rpx;
        height: 80rpx;
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        margin-left: 20rpx;

        &.cancel {
          background-color: #f5f5f5;
          color: #666;
        }

        &.submit {
          background-color: $theme-color;
          color: #fff;
        }
      }
    }
  }
}
</style>
